﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Media;

namespace DynamicUIFramework
{
    public class DragThumb : Thumb
    {
        //1像素=3/4磅
        static readonly int step = 6;

        public DragThumb()
        {
            base.DragDelta += new DragDeltaEventHandler(DragThumb_DragDelta);
        }
        void DragThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            DesignerItem designerItem = this.DataContext as DesignerItem;
            Canvas canvas = VisualTreeHelper.GetParent(designerItem) as Canvas;
            if (designerItem != null && canvas != null)
            {
                double minLeft = double.MaxValue;
                double minTop = double.MaxValue;

                double left = Canvas.GetLeft(designerItem);
                double top = Canvas.GetTop(designerItem);

                minLeft = double.IsNaN(left) ? 0 : Math.Min(left, minLeft);
                minTop = double.IsNaN(top) ? 0 : Math.Min(top, minTop);

                double deltaHorizontal = Math.Max(-minLeft, e.HorizontalChange);
                double deltaVertical = Math.Max(-minTop, e.VerticalChange);

                deltaHorizontal = ((int)deltaHorizontal / step) * step;
                if ((int)deltaHorizontal % step >= step / 2)
                    deltaHorizontal += step;

                deltaVertical = ((int)deltaVertical / step) * step;
                if ((int)deltaVertical % step >= step / 2)
                    deltaVertical += step;

                double left1 = Canvas.GetLeft(designerItem);
                double top1 = Canvas.GetTop(designerItem);

                if (double.IsNaN(left1)) left1 = 0;
                if (double.IsNaN(top1)) top1 = 0;

                Canvas.SetLeft(designerItem, left1 + deltaHorizontal);
                Canvas.SetTop(designerItem, top1 + deltaVertical);

                canvas.InvalidateMeasure();
                e.Handled = true;
            }
        }
    }
}
